//
//  MBDAccountInfoModel.swift
//  MasterBoy
//
//  Created by kyson on 2023/4/22.
//

import Foundation
import SwiftyJSON

class MBDAccountInfoModel : NSObject,Encodable,Decodable {
    
    var userId : String!
    var phoneNumber : String!
    var realName : String!
    var avatarUrl : String!
    var weChatNumber : String!
    var weChatNumberOcr : String!
    
    
    override init() {
        super.init()
    }
    
    init(_ jsonData : JSON) {
        super.init()
        
        self.userId = jsonData["userId"].stringValue
        self.phoneNumber = jsonData["phoneNumber"].stringValue
        self.realName = jsonData["realName"].stringValue
        self.avatarUrl = jsonData["avatarUrl"].stringValue
        self.weChatNumber = jsonData["weChatNumber"].stringValue
        self.weChatNumberOcr = jsonData["weChatNumberOcr"].stringValue
    }
    
    static func clear(){
        UserDefaults.standard.removeObject(forKey: "userAccount")
    }
    
    
    private func save(){
        do {
            try UserDefaults.standard.setModelObject(self, forKey: "userAccount")
        }catch {
        }
    }
    
    static func current() ->MBDAccountInfoModel? {
        do {
            let current = try UserDefaults.standard.getModelObject(forKey: "userAccount", castTo: MBDAccountInfoModel.self)
            return current
        } catch {
            
        }
        return nil
    }
    
    private static func doUserInfoRequest(completion : @escaping (_ error : NSError?,_ result:MBDAccountInfoModel?)->()) {
        
        MBDHttpClient.shared.request("/user/getInfo").httpClientResponse { error, response in
            if nil != error {
                completion(error,nil)
            } else {
                let rawDict = response?.rawDict
                let userInfo = rawDict?["data"]
                let item = MBDAccountInfoModel(JSON(rawValue: userInfo ?? Dictionary<String, Any>()) ?? JSON(NSObject()))
                completion(nil,item)
            }
        }
    }
    
    func update(notify: Bool){
        MBDAccountInfoModel.self.doUserInfoRequest { error,result in
            result?.save()
            
            if(notify) {
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "UserInfoUpdated"), object: nil)
            }
        }
    }
    
    static func fetch(){
        MBDAccountInfoModel.self.doUserInfoRequest { error,result in
            result?.save()
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "UserInfoUpdated"), object: nil)
        }
    }
}
